import { _decorator, Button, CCInteger, Component, Node, tween, UIOpacity, UITransform } from 'cc';
import { GameDefine } from './GameDefine';
const { ccclass, property } = _decorator;

/** 无线滚动大地图 */
@ccclass('MapManager')
export class MapManager extends Component {
    public static Instance: MapManager = null;
    onLoad() {
        MapManager.Instance = this;
    }

    @property(Node) map1: Node = null!;
    @property(Node) map2: Node = null!;
    @property(Node) map3: Node = null!;
    moveSpeed: number = 20;
    private mapIndex: number = 1;
    private mapItemList: Node[] = [];
    private curMap: Node = null!;

    start() {
        this.curMap = this.map1;
        this.mapItemList = this.curMap.children;
    }

    public stopMove() {
        tween({ value: this.moveSpeed })
            .to(1, { value: 0 })
            .call((target) => {
                this.moveSpeed = target.value;
            })
            .start();
    }

    public changeMap() {
        if (this.mapIndex >= 3)
            return;

        const curOp = this.curMap.getComponent(UIOpacity);
        tween(curOp).to(1, { opacity: 0 }).start();
        this.mapIndex++;
        this.curMap = this.mapIndex == 2 ? this.map2 : this.map3;
        this.mapItemList = this.curMap.children;
        const nextOp = this.curMap.getComponent(UIOpacity);
        tween(nextOp).to(0.5, { opacity: 255 }).start();
    }

    update(dt: number) {
        if (GameDefine.isGamePaused)
            return;

        const moveStep = this.moveSpeed * dt;
        for (let m of this.mapItemList) {
            m.setPosition(m.position.x - moveStep, m.position.y, m.position.z);
        }
        if (this.mapItemList.length < 2) return;
        const mapWidth = this.mapItemList[0].getComponent(UITransform)?.contentSize.width || 0;
        for (let i = 0; i < this.mapItemList.length; i++) {
            if (this.mapItemList[i].position.x <= -mapWidth * 1.1) {
                let maxX = Math.max(...this.mapItemList.map(m => m.position.x));
                this.mapItemList[i].setPosition(maxX + mapWidth, this.mapItemList[i].position.y, this.mapItemList[i].position.z);
            }
        }
    }
}


